package com.sunnos.express.controller;

import java.io.IOException;

import java.util.HashMap;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sunnos.express.entity.Right;
import com.sunnos.express.entity.Role;
import com.sunnos.express.entity.User;
import com.sunnos.express.service.RoleService;
import com.sunnos.express.service.UserService;

@Controller
@RequestMapping("/user")
public class UserController {
	@Autowired
	private UserService userService;
	@Autowired
	private RoleService roleService;

	/**
	 * ��¼��֤
	 * @param request
	 * @param response
	 * @param user
	 * @return
	 */
	@RequestMapping(value="/login",method=RequestMethod.POST)
	public @ResponseBody Map<String,String> loginCheck(HttpServletRequest request,   
			HttpServletResponse response){
		//spring������jackson�Զ�������ֵ��װ��JSON����
		Map<String,String> responseMap = new HashMap<String,String>();
		//String captcha = request.getParameter("captcha");
		String account = request.getParameter("account");
		String password = request.getParameter("passwd");
		//String vcode = (String)request.getSession().getAttribute("vcode");
		//	if(vcode==null || !captcha.equals(vcode)) {
		//		responseMap.put("success", "false");
		//		responseMap.put("info", "��֤�����");
		//		return responseMap;
		//	}
		try {
			Map<String,Object> param = new HashMap<String,Object>();
			param.put("account", account);
			param.put("password", password);
			User user = userService.getUser(param);
			if(user!=null) {
				responseMap.put("success", "true");
				responseMap.put("info", "��¼�ɹ���");
				param.put("id", user.getRole().getId());
				Role role = roleService.getRole(param);
				request.getSession().setAttribute("user", user); 
				request.getSession().setAttribute("loginUserName", user.getName()); 
				request.getSession().setAttribute("loginUserRole", role); 
				request.getSession().setAttribute("loginUserRoleName", user.getRole().getName());
				return responseMap;
			}else {
				responseMap.put("success", "false");
				responseMap.put("info", "�û�����������");
				return responseMap;
			}
		}catch(Exception e) {
			e.printStackTrace();
			responseMap.put("info", e.getClass()+":"+e.getMessage());
			return responseMap;
		}
	}
	
	/**
	 * ��ȡ���в˵�
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="/menus",method=RequestMethod.POST)
	public @ResponseBody Map<String,Object> getMenus(HttpServletRequest request,   
            HttpServletResponse response){
		Map<String,Object> responseMap = new HashMap<String,Object>();
		String path = request.getContextPath();
		User user = (User)request.getSession().getAttribute("user");
		List<Right> list = userService.getUserMenus(user.getRole().getId());
		List<Hashtable<String,String>> menus = new ArrayList<Hashtable<String,String>>();
		StringBuffer sb = new StringBuffer();
		for(int i = 0 ; i < list.size() ; i++){
			Right right = list.get(i);
			if(right.getChildNode().size()>0){
				Hashtable<String,String> h = new Hashtable<String,String>();
				h.put("title","<b>"+right.getName()+"</b>");
				h.put("collapsed","true");
				h.put("autoScroll","true");
				for(int j = 0 ; j < right.getChildNode().size() ; j++){
					Right subRight = right.getChildNode().get(j);
					sb.append("<div class=changPage style=\"background-color:#9EBFEA;padding:4px;margin:0px 0px -13px 0px\"><a href=\"javascript:goPage('"+subRight.getId()+"','"+subRight.getName()+"','"+path+subRight.getUrl()+"')\">"+subRight.getName()+"</a></div></br>");
				}
				h.put("html", sb.toString());
				sb.delete(0, sb.toString().length());
				menus.add(h);
			}
		}
		responseMap.put("success", "true");
		responseMap.put("data", menus);
		return responseMap;
	}
	
	/**
	 * ��ȡsessions��Ϣ
	 * @param request
	 * @param response
	 * @param user
	 * @return
	 */
	@RequestMapping(value="/getSessionUser",method=RequestMethod.POST)
	public @ResponseBody Map<String,Object> getSessionUser(HttpServletRequest request,   
			HttpServletResponse response){
		//spring������jackson�Զ�������ֵ��װ��JSON����
		Map<String,Object> responseMap = new HashMap<String,Object>();
		User user = (User)request.getSession().getAttribute("user");
		Role role = (Role)request.getSession().getAttribute("loginUserRole");
		if (user==null) {
			responseMap.put("success", "false");
			responseMap.put("msg", "failure");
		}
		else {
			responseMap.put("success", "true");
			responseMap.put("msg", "ok");
//			responseMap.put("data", user.getAccount());
			responseMap.put("role", role);
			responseMap.put("user", user);
		}
		return responseMap;
	}
	
	/**
	 * ��ɾ���û�
	 * @param request
	 * @param response
	 * @param user
	 * @return
	 */
	@RequestMapping(value="/delete",method=RequestMethod.POST)
	public @ResponseBody Map<String,String> delete(HttpServletRequest request,   
			HttpServletResponse response){
		//spring������jackson�Զ�������ֵ��װ��JSON����
		Map<String,String> responseMap = new HashMap<String,String>();
		String id = request.getParameter("id");		
		try {
			System.out.println("ids is...."+id);
			userService.deleteUser(id);
			responseMap.put("msg", "ok");
			responseMap.put("success", "true");
			return responseMap;
		}catch(Exception e) {
			e.printStackTrace();
			responseMap.put("msg", "failure");
			responseMap.put("success", "false");
			responseMap.put("errors", e.getClass()+":"+e.getMessage());
			return responseMap;
		}
	}
	
	/**
	 * ��ӻ��޸��û�
	 * @param request
	 * @param response
	 * @param user
	 * @return
	 */
	@RequestMapping(value="/save",method=RequestMethod.POST)
	public @ResponseBody Map<String,String> save(HttpServletRequest request,   
			HttpServletResponse response){
		//spring������jackson�Զ�������ֵ��װ��JSON����
		Map<String,String> responseMap = new HashMap<String,String>();
		String id = request.getParameter("id");
		String account = request.getParameter("account");
		String password = request.getParameter("password");
		String name = request.getParameter("name");
		String roleId = request.getParameter("roleId");
		try {
			if (id==null || "".equals(id)) {
				User user = new User();
//				user.setAccount(account);
//				user.setName(name);
//				user.setPassword(password);
				Map<String,Object> param = new HashMap<String,Object>();
				param.put("id", roleId);
				Role role = roleService.getRole(param);
				user.setRole(role);
				userService.insertUser(user);				
			}
			else {
				User user = new User();
//				user.setId(Integer.parseInt(id));
				user.setName(name);
				Map<String,Object> param = new HashMap<String,Object>();
				param.put("id", roleId);
				Role role = roleService.getRole(param);
				user.setRole(role);
				userService.updateUser(user);			
			}
			responseMap.put("msg", "ok");
			responseMap.put("success", "true");
			return responseMap;
		}catch(Exception e) {
			e.printStackTrace();
			responseMap.put("msg", "failure");
			responseMap.put("success", "false");
			responseMap.put("errors", e.getClass()+":"+e.getMessage());
			return responseMap;
		}
	}
	
	/**
	 * ����û��˺��Ƿ�ע��
	 * @param request
	 * @param response
	 * @param user
	 * @return
	 */
	@RequestMapping(value="/checkAccount",method=RequestMethod.POST)
	public @ResponseBody Map<String,String> checkAccount(HttpServletRequest request,   
			HttpServletResponse response){
		//spring������jackson�Զ�������ֵ��װ��JSON����
		Map<String,String> responseMap = new HashMap<String,String>();
		String account = request.getParameter("id");
		try {
			Map<String,Object> param = new HashMap<String,Object>();
			param.put("account", account);
			User user = userService.getUser(param);
			if(user!=null) {
				responseMap.put("msg", "ok");
				responseMap.put("info", "�û��˺Ŵ���");
				return responseMap;
			}else {
				responseMap.put("msg", "failure");
				responseMap.put("info", "�û��˺Ų�����");
				return responseMap;
			}
		}catch(Exception e) {
			e.printStackTrace();
			responseMap.put("msg", "failure");
			responseMap.put("info", e.getClass()+":"+e.getMessage());
			return responseMap;
		}
	}
	
	/**
	 * ��ȡָ���û�����
	 * @param request
	 * @param response
	 * @param user
	 * @return
	 */
	@RequestMapping(value="/getUser",method=RequestMethod.POST)
	public @ResponseBody Map<String,Object> getUser(HttpServletRequest request,   
			HttpServletResponse response){
		//spring������jackson�Զ�������ֵ��װ��JSON����
		Map<String,Object> responseMap = new HashMap<String,Object>();
		String id = request.getParameter("id");
		try {
			Map<String,Object> param = new HashMap<String,Object>();
			param.put("id", id);
			User user = userService.getUser(param);
			if(user!=null) {
				responseMap.put("success", "true");
				responseMap.put("info", "��¼�ɹ���");
				responseMap.put("user", user);
				return responseMap;
			}else {
				responseMap.put("success", "false");
				responseMap.put("info", "�û�������");
				return responseMap;
			}
		}catch(Exception e) {
			e.printStackTrace();
			responseMap.put("info", e.getClass()+":"+e.getMessage());
			return responseMap;
		}
	}
	
	/**
	 * �޸�������֤������
	 * @param request
	 * @param response
	 * @param user
	 * @return
	 */
	@RequestMapping(value="/validOldPwd",method=RequestMethod.POST)
	public @ResponseBody Map<String,String> validOldPwd(HttpServletRequest request,   
			HttpServletResponse response){
		//spring������jackson�Զ�������ֵ��װ��JSON����
		Map<String,String> responseMap = new HashMap<String,String>();
		String account = request.getParameter("id");
		String password = request.getParameter("oldPasswd");
		try {
			Map<String,Object> param = new HashMap<String,Object>();
			param.put("account", account);
			param.put("password", password);
			User user = userService.getUser(param);
			if(user!=null) {
				responseMap.put("success", "true");
				responseMap.put("info", "��¼�ɹ���");
				return responseMap;
			}else {
				responseMap.put("success", "false");
				responseMap.put("info", "�û�����������");
				return responseMap;
			}
		}catch(Exception e) {
			e.printStackTrace();
			responseMap.put("info", e.getClass()+":"+e.getMessage());
			return responseMap;
		}
	}
	
	/**
	 * �޸�����
	 * @param request
	 * @param response
	 * @param user
	 * @return
	 */
	@RequestMapping(value="/updatePwd",method=RequestMethod.POST)
	public @ResponseBody Map<String,String> updatePwd(HttpServletRequest request,   
			HttpServletResponse response){
		//spring������jackson�Զ�������ֵ��װ��JSON����
		Map<String,String> responseMap = new HashMap<String,String>();
		String account = request.getParameter("id");
		String password = request.getParameter("newpwd");
		try {
			Map<String,Object> param = new HashMap<String,Object>();
			param.put("id", account);
			param.put("newPassword", password);
			userService.changeUserPassword(param);
			responseMap.put("success", "true");
			responseMap.put("info", "�޸ĳɹ�");
			return responseMap;
		}catch(Exception e) {
			e.printStackTrace();
			responseMap.put("success", "false");
			responseMap.put("info", e.getClass()+":"+e.getMessage());
			return responseMap;
		}
	}
	
	/**
	 * ��ʼ���û�����
	 * @param request
	 * @param response
	 * @param user
	 * @return
	 */
	@RequestMapping(value="/initpwd",method=RequestMethod.POST)
	public @ResponseBody Map<String,String> initpwd(HttpServletRequest request,   
			HttpServletResponse response){
		//spring������jackson�Զ�������ֵ��װ��JSON����
		Map<String,String> responseMap = new HashMap<String,String>();
		String account = request.getParameter("id");
		try {
			Map<String,Object> param = new HashMap<String,Object>();
			param.put("id", account);
			param.put("newPassword", "123456");
			userService.changeUserPassword(param);
			responseMap.put("msg", "ok");
			responseMap.put("info", "�޸ĳɹ�");
			return responseMap;
		}catch(Exception e) {
			e.printStackTrace();
			responseMap.put("msg", "failure");
			responseMap.put("info", e.getClass()+":"+e.getMessage());
			return responseMap;
		}
	}
	
	/**
	 * �޸�����
	 * @param request
	 * @param response
	 * @param user
	 * @return
	 */
	@RequestMapping(value="/logout",method=RequestMethod.GET)
	public @ResponseBody void logout(HttpServletRequest request,   
			HttpServletResponse response){
		//spring������jackson�Զ�������ֵ��װ��JSON����
		request.removeAttribute("user");
		request.removeAttribute("loginUserName");
		request.removeAttribute("loginUserRole");
		request.getSession().invalidate();
		try {
			response.sendRedirect(request.getContextPath()+"/index.jsp");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/**
	 * ��ѯ�û��б�
	 * @param request
	 * @param response
	 * @param user
	 * @return
	 */
	@RequestMapping(value="/list",method=RequestMethod.POST)
	public @ResponseBody Map<String,Object> list(HttpServletRequest request,   
			HttpServletResponse response){
		//spring������jackson�Զ�������ֵ��װ��JSON����
		Map<String,Object> responseMap = new HashMap<String,Object>();
		String start2 = request.getParameter("start");//��ǰҳ��һ����ݵ�����
		String limit = request.getParameter("limit");//ÿҳ����
		int start = Integer.parseInt(start2);
		int pageSize = Integer.parseInt(limit);
		//int pageNo = start/pageSize+1;
		int end = start+pageSize;
		String account = request.getParameter("account");
		String name = request.getParameter("name");
		//System.out.println("parameters............(start2,limit,start,end,account,name)="+start2+","+limit+","+start+","+end+","+account+","+name);
		try {
			Map<String,Object> param = new HashMap<String,Object>();
			param.put("account", account);
			param.put("name", name);
			param.put("offset", start);
			param.put("limitSize", end);
			int totalCount = userService.getUserListTotal(param);
			List<User> ret = userService.getUserList(param);
			responseMap.put("rows", ret);
			responseMap.put("totalCount", totalCount);
			responseMap.put("success", "true");
			return responseMap;
		}catch(Exception e) {
			e.printStackTrace();
			responseMap.put("success", "false");
			responseMap.put("info", e.getClass()+":"+e.getMessage());
			return responseMap;
		}
	}
	
	/**
	 * ��ѯ�û��б�
	 * @param request
	 * @param response
	 * @param user
	 * @return
	 */
	@RequestMapping(value="/listAll")
	public @ResponseBody Map<String,Object> listAll(HttpServletRequest request,   
			HttpServletResponse response){
		//spring������jackson�Զ�������ֵ��װ��JSON����
		Map<String,Object> responseMap = new HashMap<String,Object>();
		try {
			Map<String,Object> param = new HashMap<String,Object>();
			int totalCount = userService.getUserListTotal(param);
			List<User> ret = userService.getUserList(param);
			responseMap.put("rows", ret);
			responseMap.put("totalCount", totalCount);
			responseMap.put("success", "true");
			return responseMap;
		}catch(Exception e) {
			e.printStackTrace();
			responseMap.put("success", "false");
			responseMap.put("info", e.getClass()+":"+e.getMessage());
			return responseMap;
		}
	}
}
